/*
 * 文件名称: AdminAction.java
 * 版权信息: Copyright 2005-2013 SKY-MOBI Inc. All right reserved.
 * ----------------------------------------------------------------------------------------------
 * 修改历史:
 * ----------------------------------------------------------------------------------------------
 * 修改原因: 新增
 * 修改人员: Allen.Hu
 * 修改日期: 2013-3-30
 * 修改内容: 
 */
package com.drzui.tickets.order.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.bigmouth.framework.util.DateUtils;
import org.bigmouth.framework.util.StringUtils;
import org.bigmouth.framework.util.json.JSONArray;
import org.bigmouth.framework.util.json.JSONObject;
import org.bigmouth.framework.web.action.json.JsonActionSupport;

import com.drzui.tickets.admin.AdminSessionUtils;
import com.drzui.tickets.admin.entity.Admin;
import com.drzui.tickets.order.entity.OrdersGoodsinfo;
import com.drzui.tickets.order.entity.OrdersInfo;
import com.drzui.tickets.order.service.OrdersGoodsinfoService;
import com.drzui.tickets.order.service.OrdersInfoService;

@Namespace("/business")
@Action("order")
@Results({@Result(name = OrdersInfoAction.ResultName.Success, location = "/WEB-INF/pages/template.vm"),
	@Result(name = OrdersInfoAction.ResultName.Produce, location = "/WEB-INF/pages/order/produce.vm"),
	@Result(name = OrdersInfoAction.ResultName.ssddtest, location = "/WEB-INF/pages/order/produce.vm"),
	@Result(name = OrdersInfoAction.ResultName.Error, location = "/base/index/index.shtml", type="redirect")})
public class OrdersInfoAction extends JsonActionSupport {

    private static final long serialVersionUID = -1183981655415621414L;

    private static final Logger logger = Logger.getLogger(OrdersInfoAction.class);

    private OrdersInfoService ordersInfoService;
    
    private OrdersGoodsinfoService ordersGoodsinfoService;
    
    private OrdersInfo ordersInfo;
    
    private OrdersGoodsinfo ordersGoodsinfo;
    
    private Admin admin;
    
	private List<OrdersInfo> listOrdersInfo;
	
	private List<OrdersGoodsinfo> listOrdersGoodsinfo;

	private String executeUrl;

	@Override
    public String execute() throws Exception {
		// 获取当前用户
		admin = AdminSessionUtils.getSession();
		
		executeUrl = "/WEB-INF/pages/order/query.vm";
		return ResultName.Success;
    }
	
	/**
	 * 查询订单 action
	 * @return
	 */
	public String query() {
		// 获取当前用户
		admin = AdminSessionUtils.getSession();
		
		// 获取查询参数
		boolean flag = getQueryPageParam();
		
		try {
			if(flag){
				listOrdersInfo = ordersInfoService.queryOrders(ordersInfo);
			}
		}
		catch (Exception e) {
		    logger.error(e);
		}
		
		executeUrl = "/WEB-INF/pages/order/query.vm";
		return ResultName.Success;
	}
	
	/**
	 * 创建新的订单 action
	 * @return
	 */
	public String toNewOrder() {
		// 获取当前用户
		admin = AdminSessionUtils.getSession();
		
		// 自动生成订单编号
		ordersInfo = new OrdersInfo();
		Integer orderid = ordersInfoService.autoOrderid();
		ordersInfo.setOrderid(orderid);
		
		executeUrl = "/WEB-INF/pages/order/newOrder.vm";
		return ResultName.Success;
	}
	
	/**
	 * 制定/查看 生产单
	 * @return
	 */
	public String produce() {
		//获取当前用户
		admin = AdminSessionUtils.getSession();
		Integer orderid = Integer.parseInt(getParameter("orderid") == null ? "0" : getParameter("orderid"));
		String goodsid = getParameter("goodsid");
		ordersInfo = new OrdersInfo();
		ordersGoodsinfo = new OrdersGoodsinfo();
		ordersInfo.setOrderid(orderid);
		ordersGoodsinfo.setOrderid(orderid);
		
		ordersInfo = ordersInfoService.getOrderByOrderid(ordersInfo.getOrderid());
		ordersGoodsinfo = ordersGoodsinfoService.getGoodsinfo(goodsid);
		
		return ResultName.Produce;
	}
	
	/**
	 * 获取订单详情以及商品详情 ajax
	 */
	public void getOrderDetail() {
		Integer orderid = Integer.parseInt(getParameter("orderid") == null ? "0" : getParameter("orderid"));
		ordersInfo = new OrdersInfo();
		ordersGoodsinfo = new OrdersGoodsinfo();
		ordersInfo.setOrderid(orderid);
		ordersGoodsinfo.setOrderid(orderid);
		
		ordersInfo = ordersInfoService.getOrderByOrderid(ordersInfo.getOrderid());
		listOrdersGoodsinfo = ordersGoodsinfoService.getOrdersGoodsinfo(ordersGoodsinfo);
		
		Map<String, Object> map = new HashMap<String, Object>();
        map.put("order", ordersInfo);
        map.put("goods", listOrdersGoodsinfo);
        succeed(map);
	}
	
	/**
	 * 新增订单信息 订单商品信息 ajax
	 */
	public void newOrder() {
		// 获取当前用户
		admin = AdminSessionUtils.getSession();

		// 获取设置参数
		getNewPageParam();
		try {
			// 根据自动生成的订单号 查询是否已存在
			OrdersInfo order = null;
			if (ordersInfo.getId() != null) {
				order = ordersInfoService.getOrderByOrderid(ordersInfo.getOrderid());
			}
			if (order == null) {
				ordersInfoService.newOrder(ordersInfo);
				ordersGoodsinfoService.newGoodsList(listOrdersGoodsinfo);
				succeed("添加成功，是否继续添加或返回!");
			} else {
				failed("添加失败，订单信息已存在，请重新添加!");
			}

		} catch (Exception e) {
			logger.error(e);
		}
	}
	
	/**
	 * 修改订单信息 订单商品信息 ajax
	 */
	public void modifyOrder() {
		// 获取当前用户
		admin = AdminSessionUtils.getSession();
		
		// 获取设置参数
		getNewPageParam();
		try{
			// 修改订单信息
			ordersInfoService.modifyOrder(ordersInfo);
			
			List<OrdersGoodsinfo> addGoods = new ArrayList();
			List<OrdersGoodsinfo> modifyGoods = new ArrayList();
			List<OrdersGoodsinfo> removeGoods = new ArrayList();
			
			for (int i = 0; i < listOrdersGoodsinfo.size(); i++) {
				// 如果id不等于0 则为修改商品信息
				if (listOrdersGoodsinfo.get(i).getId() != 0) {
					// 如果isRemove 等于0 则不删除
					if(listOrdersGoodsinfo.get(i).getIsRemove() == 0) {
						modifyGoods.add(listOrdersGoodsinfo.get(i));
					} else {
						removeGoods.add(listOrdersGoodsinfo.get(i));
					}
					
				} else {
					addGoods.add(listOrdersGoodsinfo.get(i));
				}
			}
			
			// 修改新增删除商品信息
			ordersGoodsinfoService.newGoodsList(addGoods);
			ordersGoodsinfoService.modifyGoodsList(modifyGoods);
			ordersGoodsinfoService.removeGoodsList(removeGoods);
			succeed();
		}
		catch (Exception e) {
		    logger.error(e);
		}
	}
	
	/**
	 * 根据订单号查询商品信息 ajax
	 */
	public void queryOrdersGoodsInfo() {
		Integer orderid = Integer.parseInt(getParameter("orderid") == null ? "0" : getParameter("orderid"));
		if (orderid != 0) {
			try{
				ordersGoodsinfo = new OrdersGoodsinfo();
				ordersGoodsinfo.setOrderid(orderid);
				listOrdersGoodsinfo = ordersGoodsinfoService.getOrdersGoodsinfo(ordersGoodsinfo);
				Map<String, Object> map = new HashMap<String, Object>();
                map.put("list", listOrdersGoodsinfo);
                succeed(map);
			}
			catch (Exception e) {
			    logger.error(e);
			}
		}
	}
	
	/**
	 * 获取查询页面参数 private
	 * 
	 */
	private boolean getQueryPageParam() {
		Integer orderid = Integer.parseInt(getParameter("orderid") == null ? "0" : getParameter("orderid"));
		String customername = getParameter("customername");
		String customeraddress = getParameter("customeraddress");
		String customerphone = getParameter("customerphone");
		Date begintime = DateUtils.convertString2Date(getParameter("begintime"), DateUtils.DEFAULT_DATE_FORMAT);
		Date endtime = DateUtils.convertString2Date(getParameter("endtime"), DateUtils.DEFAULT_DATE_FORMAT);
		String orderbyclause = getParameter("orderbyclause");
		
		// 如果没有查询条件 则不查询
		boolean flag = false;
		ordersInfo = new OrdersInfo();
		
		if (orderid != 0) {
			ordersInfo.setOrderid(orderid);
			flag = true;
		}
		
		if(!StringUtils.isEmpty(customername)){
			try {
				ordersInfo.setCustomername(StringUtils.getEncodedString(customername));
				flag = true;
			} catch (Exception e) {
				logger.error(e);
			}
		}
		
		if(!StringUtils.isEmpty(customeraddress)){
			try {
				ordersInfo.setCustomeraddress(StringUtils.getEncodedString(customeraddress));
				flag = true;
			} catch (Exception e) {
				logger.error(e);
			}
		}
		
		if(!StringUtils.isEmpty(customerphone)){
			try {
				ordersInfo.setCustomerphone(StringUtils.getEncodedString(customerphone));
				flag = true;
			} catch (Exception e) {
				logger.error(e);
			}
		}
		
		if(begintime != null){
			ordersInfo.setBegintime(begintime);
			flag = true;
		}
		
		if(endtime != null){
			ordersInfo.setEndtime(endtime);
			flag = true;
		}
		
		if(!StringUtils.isEmpty(orderbyclause)){
			try {
				ordersInfo.setOrderbyclause(StringUtils.getEncodedString(orderbyclause));
			} catch (Exception e) {
				logger.error(e);
			}
		} else {
			// 默认排序方式
			ordersInfo.setOrderbyclause("orderid ASC");
		}
		
		return flag;
	}
	
	/**
	 * 获取新增页面参数
	 * @throws  
	 */
	private void getNewPageParam() {
		Integer id = Integer.parseInt(getParameter("id") == null ? "0" : getParameter("id"));
		Integer orderid = Integer.parseInt(getParameter("orderid"));
		String agents = getParameter("agents");
		String customername = getParameter("customername");
		String customeraddress = getParameter("customeraddress");
		String customerphone = getParameter("customerphone");
		Integer paidmoney = Integer.parseInt(getParameter("paidmoney"));
		Integer allmoney = Integer.parseInt(getParameter("allmoney"));
		Integer process = Integer.parseInt(getParameter("process"));
		Integer isexpedited = Integer.parseInt(getParameter("isexpedited"));
		Date begintime = DateUtils.convertString2Date(getParameter("begintime"), DateUtils.DEFAULT_DATE_FORMAT);
		Date endtime = DateUtils.convertString2Date(getParameter("endtime"), DateUtils.DEFAULT_DATE_FORMAT);
		Date createtime = DateUtils.getCurrentDate();
		String remark = getParameter("remark");
		
		ordersInfo = new OrdersInfo();
		// id不等于0时为修改订单信息
		if(id != 0) {
			ordersInfo.setId(id);
		}
		ordersInfo.setOrderid(orderid);
		ordersInfo.setAgents(agents);
		ordersInfo.setCustomername(customername);
		ordersInfo.setCustomerphone(customerphone);
		ordersInfo.setCustomeraddress(customeraddress);
		ordersInfo.setPaidmoney(paidmoney);
		ordersInfo.setAllmoney(allmoney);
		ordersInfo.setProcess(process);
		ordersInfo.setIsexpedited(isexpedited);
		ordersInfo.setCreatetime(createtime);
		ordersInfo.setBegintime(begintime);
		ordersInfo.setEndtime(endtime);
		ordersInfo.setRemark(remark);
		
		try {
			String goodsList = getParameter("goodsList");
			JSONArray json = new JSONArray(goodsList);
			listOrdersGoodsinfo = new ArrayList();
			for (int i = 0; i < json.length(); i++) {
				ordersGoodsinfo = new OrdersGoodsinfo();
				JSONObject obj = json.getJSONObject(i);
				
				ordersGoodsinfo.setId(StringUtils.isEmpty(obj.getString("id")) ? 0 : obj.getInt("id"));
				ordersGoodsinfo.setOrderid(orderid);
				ordersGoodsinfo.setGoodsid(obj.getString("goodsid"));
				ordersGoodsinfo.setGoodsmaterial(obj.getString("goodsmaterial"));
				ordersGoodsinfo.setGoodscolor(obj.getString("goodscolor"));
				ordersGoodsinfo.setGoodsstyle(obj.getString("goodsstyle"));
				ordersGoodsinfo.setAmount(StringUtils.isEmpty(obj.getString("amount")) ? 0 : obj.getInt("amount"));
				ordersGoodsinfo.setPrice(StringUtils.isEmpty(obj.getString("price")) ? 0 : obj.getInt("price"));
				ordersGoodsinfo.setProcess(StringUtils.isEmpty(obj.getString("process")) ? 0 : obj.getInt("process"));
				ordersGoodsinfo.setGoodstype(StringUtils.isEmpty(obj.getString("goodstype")) ? 0 : obj.getInt("goodstype"));
				ordersGoodsinfo.setGoodssize(obj.getString("goodssize"));
				ordersGoodsinfo.setGoodspic(obj.getString("goodspic"));
				ordersGoodsinfo.setRemark(obj.getString("remark"));
				ordersGoodsinfo.setIsRemove(StringUtils.isEmpty(obj.getString("isRemove")) ? 0 : obj.getInt("isRemove"));
				listOrdersGoodsinfo.add(ordersGoodsinfo);
			}
		}
		catch (Exception e) {
		    logger.error(e);
		}
	}
	
	public interface ResultName {
		String Error = "Error";
        String Success = "Success";
        String Produce = "Produce";
        String ssddtest = "ssddtest";
    }
	
	public OrdersInfoService getOrdersInfoService() {
		return ordersInfoService;
	}

	public void setOrdersInfoService(OrdersInfoService ordersInfoService) {
		this.ordersInfoService = ordersInfoService;
	}

	public OrdersInfo getOrdersInfo() {
		return ordersInfo;
	}

	public void setOrdersInfo(OrdersInfo ordersInfo) {
		this.ordersInfo = ordersInfo;
	}

	public String getExecuteUrl() {
		return executeUrl;
	}

	public void setExecuteUrl(String executeUrl) {
		this.executeUrl = executeUrl;
	}
	
	public List<OrdersInfo> getListOrdersInfo() {
		return listOrdersInfo;
	}

	public void setListOrdersInfo(List<OrdersInfo> listOrdersInfo) {
		this.listOrdersInfo = listOrdersInfo;
	}
	
    public Admin getAdmin() {
		return admin;
	}

	public void setAdmin(Admin admin) {
		this.admin = admin;
	}
	
	public OrdersGoodsinfoService getOrdersGoodsinfoService() {
		return ordersGoodsinfoService;
	}

	public void setOrdersGoodsinfoService(
			OrdersGoodsinfoService ordersGoodsinfoService) {
		this.ordersGoodsinfoService = ordersGoodsinfoService;
	}

	public OrdersGoodsinfo getOrdersGoodsinfo() {
		return ordersGoodsinfo;
	}

	public void setOrdersGoodsInfo(OrdersGoodsinfo ordersGoodsinfo) {
		this.ordersGoodsinfo = ordersGoodsinfo;
	}

	public List<OrdersGoodsinfo> getListOrdersGoodsinfo() {
		return listOrdersGoodsinfo;
	}

	public void setListOrdersGoodsinfo(List<OrdersGoodsinfo> listOrdersGoodsinfo) {
		this.listOrdersGoodsinfo = listOrdersGoodsinfo;
	}
}
